package org.hy.corn_task.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 */
@Configuration
public class TaskExecutePool {

    @Value("${thread-pool-config.core-pool-size}")
    private Integer CORE_POOL_SIZE;

    @Value("${thread-pool-config.max-pool-size}")
    private Integer MAX_POOL_SIZE;

    @Value("${thread-pool-config.queue-capacity}")
    private Integer QUEUE_CAPACITY;

    @Value("${thread-pool-config.keep-alive-seconds}")
    private Integer KEEP_ALIVE_SECONDS;

    @Value("${thread-pool-config.thread-name-prefix}")
    private String THREAD_NAME_PREFIX;

    @Bean(name = "my-task-pool")
    public Executor myTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE); //核心线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);  //最大线程数
        executor.setQueueCapacity(QUEUE_CAPACITY); //队列大小
//        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS); //线程最大空闲时间
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
        executor.initialize();
        return executor;
    }
}